package fun.sboy.headacheMemo.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.util.ObjectUtils;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * 生成token
 */
public class TokenUtil {

    private static String SECURITY_KEY = "Dpengchen@163.comwumengtingchen5";

    private static Long EXPIRE_TIME = 1000 * 60 * 60 * 24L;// 过期时间

    public static SecretKey secretKey() {
        return Keys.hmacShaKeyFor(SECURITY_KEY.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 生成token
     *
     * @param sub        保存的主题
     * @param expireTime
     * @return
     */
    public static String generatorToken(String sub, Long expireTime) {
        Date date = new Date();
        Date expire;
        if (ObjectUtils.isEmpty(expireTime)){
            expire = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        }else{
            expire = new Date(System.currentTimeMillis() + expireTime);
        }
        return Jwts.builder()
                .setSubject(sub)
                .setIssuer("dpengchen")
                .setIssuedAt(date)
                .setExpiration(expire)
                .signWith(secretKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static Claims parseToken(String token) {
        return Jwts.parser().setSigningKey(secretKey()).parseClaimsJws(token).getBody();
    }

    public static void main(String[] args) {
        String sub = "chen";
        String token = generatorToken(sub, null);
        System.out.printf("token：%s\n",token);
        Claims claims = parseToken(token);
        System.out.printf("解析后的：%s\n", claims.getSubject());
    }
}
